﻿using Fuse8.DomainFramework.Common.Locator;

namespace Fuse8.DomainFramework.DataAccess.SqlDatabase
{
	/// <summary>
    /// Facade for <see cref="ISqlSchemaBuilder"/>
	/// </summary>
    public static class SchemaBuilder
	{
		private static ISqlSchemaBuilderChain _chain;
	    private static bool _mainBuilderSet;

	    /// <summary>
        /// Current builder
        /// </summary>
		public static ISqlSchemaBuilder Current
		{
			get
			{
                if (!_mainBuilderSet)
                {
                    var main = DependencyServiceLocator.Current.IsRegistered<ISqlSchemaBuilder>()
                                   ? DependencyServiceLocator.Current.GetInstance<ISqlSchemaBuilder>()
                                   : new MsSqlSchemaBuilder();

                    Chain.AddDefault(main);
                    _mainBuilderSet = true;
                }
			    return Chain;
			}
		}

        /// <summary>
        /// 
        /// </summary>
        /// <param name="successor"></param>
        public static void SetSuccessor(ISqlSchemaBuilder successor)
        {
            Chain.Add(successor);
        }

        private static ISqlSchemaBuilderChain Chain
	    {
            get
            {
                return _chain ??
                       (_chain =
                        DependencyServiceLocator.Current.IsRegistered<ISqlSchemaBuilderChain>()
                            ? DependencyServiceLocator.Current.GetInstance<ISqlSchemaBuilderChain>()
                            : new SqlSchemaBuilderWithChain());
            }	        
	    }
	}
}